The if statement allows to execute a block of code only if a certain condition is true. If the condition is false, the code block will be skipped.
if (condition) {
// Code to execute when the condition is true
}
#include <stdio.h>
int main()
{
int num = 10;
if (num > 0)
{
printf("The number is positive.\n");
}
printf("This statement is always executed.\n");
return 0;
}
In this example, the program checks if num is greater than 0 using the if statement. If the condition is true, it prints "The number is positive." Otherwise, it moves to the next statement, which is "This statement is always executed." Regardless of whether the condition is true or false, the second printf statement will always be executed.
The if-else statement allows to execute one block of code when a condition is true and another block of code when the condition is false.
if (condition)
{
// Code to execute when the condition is true
}
else
{
// Code to execute when the condition is false
}
#include <stdio.h>
int main() {
int num = -5;
if (num > 0) {
printf("The number is positive.\n");
} else {
printf("The number is non-positive.\n");
}
printf("This statement is always executed.\n");
return 0;
}
In this example, the program checks if num is greater than 0 using the if statement. If the condition is true, it prints "The number is positive." Otherwise, it executes the code inside the else block, which prints "The number is non-positive." Finally, the program moves to the next statement, which is "This statement is always executed."
A nested if statement is an if statement inside another if or else block. It allows to check multiple conditions one after another.
if (condition1) {
// Code to execute when condition1 is true
if (condition2) {
// Code to execute when both condition1 and condition2 are true
}
}
#include <stdio.h>
int main()
{
int num = 5;
if (num > 0)
{
printf("The number is positive.\n");
if (num % 2 == 0)
{
printf("The number is even.\n");
}
else
{
printf("The number is odd.\n");
}
}
else
{
printf("The number is non-positive.\n");
}
return 0;
}
In this example, the program first checks if num is greater than 0 using the outer if statement. If the condition is true, it prints "The number is positive." Then, it goes inside the nested if statement to check if num is even or odd. Depending on the value of num, it will print either "The number is even" or "The number is odd." If the condition in the outer if is false, the program will print "The number is non-positive."
What is the purpose of an 'if' statement in C?
What keyword is used for the 'else' part of an 'if-else' statement?
What is the result of an 'if' condition that evaluates to 'false'?
What symbol represents 'not equal to' in a C 'if' statement condition?
What construct allows multiple conditions to be evaluated in sequence?